package com.horton;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;

public class FilterMain {

    public static String rootPath = "/Users/horton/IdeaProjects/WhiteListFileFilter/target/";
    public static String drlPath = "undwrt/drl/";
    public static HashSet<String> nameSet = new HashSet<>();
    public static String myUM = "ex-horton";

    public static void main(String[] args) throws ZipException {
        ZipFile zipFile = new ZipFile(rootPath + "WhiteListFileFilter-1.0-SNAPSHOT.jar");
        extractFileFromZip(zipFile);
        zipFile.removeFile(drlPath);
        addFolderToZip(zipFile);
    }

    //1、解压压缩包中的白名单文件到当前目录
    public static void extractFileFromZip(ZipFile zipFile) throws ZipException {
        for (String whiteName : nameSet) {
            zipFile.extractFile(drlPath + whiteName + ".drl", rootPath);
        }
    }

    //3、往压缩包里添加白名单文件（整个文件夹）
    public static void addFolderToZip(ZipFile zipFile) throws ZipException {
        File file = new File(rootPath + "undwrt/");
        zipFile.addFolder(file);
    }

    public static HashSet<String> getAllKeyFromFolder() {
        File folder = new File(rootPath);
        Collection<File> files = FileUtils.listFiles(folder, new String[]{"sql"}, false);
        for (File file : files) {
            if (myUM.isEmpty()) {
                getKeyFromFile(file);
            } else {
                if (file.getName().contains(myUM)) {
                    getKeyFromFile(file);
                }
            }
        }
        return nameSet;
    }

    public static void getKeyFromFile(File file) {
        List<String> lines = null;
        try {
            lines = FileUtils.readLines(file, "UTF-8"); //一行一行读取
        } catch (IOException e) {
            e.printStackTrace();
        }
        assert lines != null;
        for (String line : lines) {
            if (line.startsWith("--")) {
                nameSet.add(line.replaceAll("--", "").trim());
            }
        }
    }
}
